package net.zjitc.controller;

import net.zjitc.domain.Category;
import net.zjitc.domain.User;
import net.zjitc.service.Impl.ServiceImpl;
import net.zjitc.service.Impl.UserImpl;
import net.zjitc.service.Service;
import net.zjitc.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import utils.dbutils.C3P0utils;
import utils.dispacher.URLMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by guo on 2017/11/29.
 */
public class UserController {
    Service service = new ServiceImpl();
    UserService userservice = new UserImpl();

    @URLMapping(url = "/userLoginUI")

    public String UserLogin(HttpServletRequest request, HttpServletResponse response) {
        List<Category> clist = service.findAllCategory();
        request.setAttribute("clist",clist);
        return "/WEB-INF/user/login.jsp";
    }

    @URLMapping(url = "/userLogin")
    public String userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String trueCode = (String) request.getSession().getAttribute("validatecode");
        String inputCode = request.getParameter("code");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userservice.findAlluser(username, password);
        if (inputCode.equalsIgnoreCase(trueCode)&&(user.getUsername().equals(username) && user.getPassword().equals(password) && user.getState() == 1)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            return "Redirect:/shop";
        }
        {
            if (!user.getUsername().equals(username)) {
                request.setAttribute("username", "你输入的用户名有误");
                return "WEB-INF/user/login.jsp";
            }
         else if (!user.getPassword().equals(password)) {
                request.setAttribute("password", "你输入的密码有误");
                return "WEB-INF/user/login.jsp";
            }
            else if(!inputCode.equalsIgnoreCase(trueCode))
            {
                request.setAttribute("Msg", "验证码有误");
                return "WEB-INF/user/login.jsp";
            }
            request.setAttribute("msg", "该账户还未激活");
            return "/WEB-INF/user/msg.jsp";
        }
    }

    @URLMapping(url = "/userRegistUI")
    public String UserRegist(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        List<Category> clist = service.findAllCategory();
        request.setAttribute("clist",clist);
        return "/WEB-INF/user/regist.jsp";
    }

    @URLMapping(url = "/userRegist")
    public String UserRegister(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        response.setContentType("text/html;charset=utf-8");
        //用户名检验

        String username = request.getParameter("username");

        QueryRunner runner = new QueryRunner(C3P0utils.getDs());
        String sql = "select * from user where username=?";
        try {
            User user = (User) runner.query(sql, new BeanHandler(User.class), username);
            if (user != null) {
                response.getWriter().print(true);
            } else {
                response.getWriter().print(false);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//验证码检验
        String trueCode = (String) request.getSession().getAttribute("validatecode");
        String inputCode = request.getParameter("code");
        if (!inputCode.equalsIgnoreCase(trueCode)) {
            request.setAttribute("Msg", "验证码错误");
            return "/WEB-INF/user/regist.jsp";
        }

        //邮箱验证
        String email = request.getParameter("email");
        String regEX = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern patternone = Pattern.compile(regEX);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcherone = patternone.matcher(email);
        // 查找字符串中是否有匹配正则表达式的字符/字符串
        boolean rsone = matcherone.find();
        if (rsone == false) {
            request.setAttribute("email", "你输入的邮箱格式有误");
            return "/WEB-INF/user/regist.jsp";
        }


        //手机号检验
        String phone = request.getParameter("phone");
        String regEx = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(phone);
        // 查找字符串中是否有匹配正则表达式的字符/字符串
        boolean rs = matcher.find();
        if (rs == false) {
            request.setAttribute("phone", "你输入的手机号格式有误");
            return "/WEB-INF/user/regist.jsp";
        }
        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
            int count = service.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("msg","注册成功，请先激活再使用");
        return "/WEB-INF/user/msg.jsp";
    }

    public String activeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");

        User user = userservice.findByCode(code);
        if (user!=null){
            user.setCode(null);
            user.setState(1);
            int count = userservice.update(user);
            request.setAttribute("msg","激活成功，请登录");
        }else {
            request.setAttribute("msg","激活失败，请先注册");
        }
        // response.getWriter().print("激活成功");
        //查询用户
        //User user = userService.findCode(code);
        //修改用户状态
        // user.setState(1);
        //更新用户
        //userService.update(user);
        return "/WEB-INF/user/msg.jsp";
    }
}

